package logic

import (
	"context"
	"encoding/json"
	"muke-chain/models/cache"
	"muke-chain/models/mysql"
	"strconv"
	"time"

	"muke-chain/mukerpc/internal/svc"
	"muke-chain/mukerpc/mukerpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListProductLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewListProductLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListProductLogic {
	return &ListProductLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ListProductLogic) ListProduct(in *mukerpc.ListProductRequest) (*mukerpc.ListProductResponse, error) {
	// todo: add your logic here and delete this line

	page, _ := strconv.Atoi(strconv.FormatInt(in.Page, 10))
	if page <= 0 {
		page = 1
	}

	pageSize, _ := strconv.Atoi(strconv.Itoa(5))
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}

	offset := (page - 1) * pageSize

	var product []mysql.Products
	query := mysql.DB.Debug().Offset(offset).Limit(pageSize).Order("created_at desc").Order("price asc")

	get := cache.Rdb.Get(l.ctx, "productList").String()
	if get == "" {
		if in.Name != "" {
			query = query.Where("name like ?", "%"+in.Name+"%").Find(&product)
		}
		query.Find(&product)

		marshal, _ := json.Marshal(product)
		cache.Rdb.Set(l.ctx, "productList", marshal, time.Hour*24)
	} else {
		json.Unmarshal([]byte(get), &product)
	}

	var productList []*mukerpc.ListProduct

	for _, products := range product {
		list := mukerpc.ListProduct{
			Name:   products.Name,
			Image:  products.Image,
			Number: products.Number,
			Price:  float32(products.Price),
			Owned:  products.Owned,
			UserId: int64(products.UserId),
		}
		productList = append(productList, &list)
	}

	return &mukerpc.ListProductResponse{List: productList}, nil
}
